package com.xuanyuan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanyuan.domain.AjaxResult;
import com.xuanyuan.entity.File;
import com.xuanyuan.entity.User;
import com.xuanyuan.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;


@Validated
@Controller
@RequestMapping("/api/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @GetMapping("/download/{fileName}")
    public void download(@NotBlank @PathVariable String fileName, HttpServletResponse response) {
        fileService.downloadFile(fileName, response);
    }

    @ResponseBody
    @RequestMapping("/page")
    public AjaxResult selectFilePage(File file, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return AjaxResult.success(new PageInfo<>(fileService.selectFileList(file)));
    }

    @ResponseBody
    @RequestMapping("/list")
    public AjaxResult selectFileList(File file) {
        return AjaxResult.success(fileService.selectFileList(file));
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult insertFile(@Validated File file, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        file.setUserId(sessionUser.getId());
        return fileService.insertFile(file);
    }

    @ResponseBody
    @PostMapping("/edit")
    public AjaxResult updateFile(@Validated File file, @NotNull(message = "文件id不能为空") Integer id, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        file.setUserId(sessionUser.getId());
        file.setId(id);
        return fileService.updateFile(file);
    }

    @ResponseBody
    @PostMapping("/removes")
    public AjaxResult deleteFileByIds(@NotEmpty(message = "文件ids不能为空") String[] ids) {
        return AjaxResult.toAjax(fileService.deleteFileByIds(ids));
    }
}

